package com.Xht.www.servlet;

//后端接收打印商家信息的请求（筛选是否被用户拉黑/是否通过管理员申请）

import com.Xht.www.config.CustomDatabaseConnectionPool;
import com.Xht.www.dao.UserBlacklistDAO;
import com.Xht.www.service.Visitor;
import com.Xht.www.serviceImpl.VisitorImpl;
import com.Xht.www.po.MerchantInfoPO;
import com.Xht.www.dao.MerchantInfoDAO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

import com.google.gson.Gson;

@WebServlet("/approved-merchants")
public class ApprovedMerchantsServlet extends HttpServlet {
    private final Visitor visitor = new VisitorImpl();
    private MerchantInfoDAO merchantInfoDAO = new MerchantInfoDAO();
    private UserBlacklistDAO blacklistDAO = new UserBlacklistDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("application/json");
        res.setCharacterEncoding("UTF-8");

        String keyword = req.getParameter("keyword");
        String searchType = req.getParameter("searchType"); // name / keyword
        String sortField = req.getParameter("sortField");
        String sortOrder = req.getParameter("sortOrder");
        int pageNumber = 1;
        int pageSize = 5;
        Long userId = null;

        try {
            pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
        } catch (Exception ignored) {}

        try {
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        } catch (Exception ignored) {}

        // 获取userId参数
        String userIdParam = req.getParameter("userId");
        if (userIdParam != null && !userIdParam.isEmpty()) {
            try {
                userId = Long.parseLong(userIdParam);
            } catch (NumberFormatException e) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的userId参数");
                return;
            }
        }

        List<MerchantInfoPO> merchants = null;
        int totalItems = 0;

        try {
            if ("name".equals(searchType)) {
                merchants = visitor.searchApprovedMerchantsByName(keyword, sortField, sortOrder, pageNumber, pageSize);
                totalItems = visitor.countApprovedMerchantsByName(keyword);
            } else if ("keyword".equals(searchType)) {
                merchants = visitor.searchApprovedMerchantsByKeyword(keyword, sortField, sortOrder, pageNumber, pageSize);
                totalItems = visitor.countApprovedMerchantsByKeyword(keyword);
            } else {
                merchants = visitor.searchApprovedMerchants(keyword, sortField, sortOrder, pageNumber, pageSize);
                totalItems = visitor.countApprovedMerchants(keyword);
            }

            // 如果userId存在，过滤掉被该用户拉黑的商家
            if (userId != null) {
                int userIdInt = userId.intValue();

                // 检查用户ID是否超出int范围
                if (userId > Integer.MAX_VALUE || userId < Integer.MIN_VALUE) {
                    res.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID超出范围");
                    return;
                }

                // 调用DAO方法（无需修改DAO）
                List<String> blacklistedMerchantNames = blacklistDAO.getUserBlacklistedMerchants(userIdInt);
                if (!blacklistedMerchantNames.isEmpty()) {
                    // 过滤商家列表
                    merchants = merchants.stream()
                            .filter(merchant -> !blacklistedMerchantNames.contains(merchant.getMerchantName()))
                            .collect(Collectors.toList());

                    // 调整总数量
                    totalItems = Math.min(totalItems - blacklistedMerchantNames.size(), totalItems);
                }
            }

            Map<String, Object> response = new HashMap<>();
            response.put("data", merchants);
            response.put("totalItems", totalItems);
            response.put("currentPage", pageNumber);
            response.put("pageSize", pageSize);

            Gson gson = new Gson();
            String json = gson.toJson(response);

            PrintWriter out = res.getWriter();
            out.print(json);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误：" + e.getMessage());
        }
    }

    @Override
    public void destroy() {
        CustomDatabaseConnectionPool.getInstance().closePool();
        super.destroy();
    }
}






